package ks.server.controllers.commands.admin.user;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.user.User;
import ks.server.controllers.requests.AckRequest;
import ks.server.controllers.requests.NackRequest;
import ks.server.persist.PersistentUserManager;
import ks.server.ServerContext;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * Process command to block a user.
 * 
 * @author Christopher Page
 */
public class UserBlockController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public UserBlockController (Communicator com) {
		this.com = com;
	}
	
	/**
	 * Process the message
	 * 
	 * @param m The message to process.
	 * @return A boolean value.
	 */
	public boolean process(Message m) {
		String originator = m.getOriginator();
		
		if (originator == null) {
			System.err.println("Originator is null.");
			return false;
		}
		
		PersistentUserManager um = ServerContext.getUserManager();
		
		if (!um.getUser(originator).isAdmin()) {
			new NackRequest(com).send(m, 4, "Access denied.", originator);
			return false;
		}
		
		Node userBlockNode = m.contents();
		
		if (userBlockNode == null || !userBlockNode.getNodeName().equalsIgnoreCase("user-block")) {
			new NackRequest(com).send(m, 4, "Unable to find user-block element.", originator);
			return false;
		}
		
		NamedNodeMap nnp = userBlockNode.getAttributes();
		Node playerNode = nnp.getNamedItem("player");
		
		if (playerNode == null) {
			new NackRequest(com).send(m, 4, "Unable to find player attribute.", originator);
			return false;
		}
		
		String player = playerNode.getNodeValue();
		
		User u = um.getUser(player);
		
		if (u == null) {
			new NackRequest(com).send(m, 4, "User, " + player + ", does not exist.", originator);
			return false;
		}
		
		u.setBlocked(true);
		if (!um.updateUser(player)) {
			new NackRequest(com).send(m, 4, "Unable to update user, " + player + ", in database.", originator);
			return false;
		}
		
		new AckRequest(com).send(m, "User, " + player + ", blocked.", originator);
		return true;
	}
}
